import Flutter

class FlutterPageBuilder {
    static func build(route: String,
                      engine:FlutterEngine,
                    arguments: [String: Any] = [:]) -> FlutterViewController {
        let engine = engine
        
        // 同步参数传递（URL方式）
        let routeWithParams = "\(route)?\(arguments.toQueryString())"
//        engine.run(withEntrypoint: nil, initialRoute: routeWithParams)
        engine.viewController = nil
        
        let vc = FlutterViewController(engine: engine, nibName: nil, bundle: nil)
        vc.setInitialRoute(route)
        // 异步参数传递（复杂数据）
        DispatchQueue.main.async {
            let channel = FlutterMethodChannel(name: "page_args/\(route)", 
                                             binaryMessenger: engine.binaryMessenger)
            channel.invokeMethod("init", arguments: arguments)
        }
        
        return vc
    }
}

extension Dictionary where Key == String, Value == Any {
    func toQueryString() -> String {
        return map { "\($0.key)=\($0.value)" }.joined(separator: "&")
    }
}
